#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include <cstdlib>
#include <ctime>

#define FIFO_FILE "chat_fifo"

int main() {
    if (access(FIFO_FILE, F_OK) != -1) {
        if (unlink(FIFO_FILE) == -1) {
            perror("unlink error");
            exit(EXIT_FAILURE);
        }
    }
    mkfifo(FIFO_FILE, 0666);
    printf("Server started. Waiting for clients...\n");
    int fd = open(FIFO_FILE, O_RDWR);
    time_t rawTime;
    struct tm* localTime;
    char timeString[128];
    char message[1024];
    while (1) {
        read(fd, message, sizeof(message));
        time(&rawTime);
        localTime = localtime(&rawTime);
        strftime(timeString, sizeof(timeString), "%H:%M:%S", localTime);
        printf("[%s Client]: %s\n", timeString, message);
        if (strcmp(message, "exit\n") == 0) break;

        printf("Server:");
        fgets(message, sizeof(message), stdin);
        write(fd, message, strlen(message) + 1);
        if (strcmp(message, "exit\n") == 0) break;
        sleep(2);
    }
    close(fd);
    unlink(FIFO_FILE);
    return 0;
}
